import { NotFound } from 'http-errors'
import Log from '@/database/models/log'

const getLogs = async (query: Query) => {
  const pageNum = Math.abs(Number(query.pageNum)) || 1
  const pageSize = Math.abs(Number(query.pageSize)) || 10
  const offset = (pageNum - 1) * pageSize
  const { count, rows } = await Log.findAndCountAll({
    order: [['id', 'DESC']],
    limit: pageSize,
    offset,
  })
  return {
    logs: rows,
    pagination: {
      total: count,
      pageNum,
      pageSize,
    },
  }
}

const getLogInfo = async (id: number) => {
  const log = await getLog(id)
  return log
}

const clearLogs = async () => {
  await Log.destroy({
    truncate: true,
  })
}

const deleteLog = async (id: number) => {
  const log = await getLog(id)
  await log.destroy()
}

/**
 * 公共方法：查询当前日志
 */
async function getLog(id: number) {
  const log = await Log.findByPk(id)
  if (!log) {
    throw new NotFound(`ID: ${id}的日志未找到。`)
  }
  return log
}

export default {
  getLogs,
  getLogInfo,
  clearLogs,
  deleteLog,
}
